package simple.tree;

import struct.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * 637. 二叉树的层平均值
 *
 * @author 刘学松
 * @date 2021-03-25 20:30
 */
public class 二叉树的层平均值 {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(2147483647);
        root.left = new TreeNode(2147483647);
        root.right = new TreeNode(2147483647);
        averageOfLevels(root);
    }

    public static List<Double> averageOfLevels(TreeNode root) {
        List<Double> list = new ArrayList<>();
        List<double[]> valueList = new ArrayList<>();
        recursion(root, valueList, 0);
        for (double[] array : valueList) {
            list.add(array[0] / array[1]);
        }
        return list;
    }

    public static void recursion(TreeNode node, List<double[]> valueList, int floor) {
        if (node != null) {
            double[] array;
            if (valueList.size() <= floor) {
                array = new double[2];
                array[0] = node.val;
                array[1] = 1;
                valueList.add(array);
            } else {
                array = valueList.get(floor);
                array[0] += node.val;
                array[1]++;
            }
            recursion(node.left, valueList, floor+1);
            recursion(node.right, valueList, floor+1);
        }
    }
}
